%% rng = selectRange (values, target, method)
%   select a threshold value that about TARGET percentage of VALUES is 
% below the threshold.
%
% values:
%   2-dimension matrix.
% target:
%   a percentage value between 0.0 & 1.0.
% method:
%   (by default) 'above' :
%     select a rng that is always above or equal the threshold.
%   'round' :
%     select a rng that is rounded to the threshold.

function rng = selectRange(values, target, method)
    if nargin < 3
        method = 'above';
    end
    
    % target is a value between 0 and 1
    [M,N] = size(values);
    va = reshape(abs(values),M*N,1);
    vmax = max(va);
    if target >= 1
        rng = vmax;
        return;
    end
    if target <= 0.0
        rng = 0;
        return;
    end
    count = 0;
    rng = 0;
    u = histc(va, 0:vmax);
    %% method 'above' : add until above target.
    if strcmp(method, 'above')
        ths = M*N*target;
        while rng < vmax
            rng = rng + 1;
            count = count+u(rng,1);
            if count >= ths
                break;
            end
        end
        return
    end
    %% method 'round' : add until reach round value.
    if strcmp(method, 'round')
        ths = round(M*N*target);
        while rng < vmax
            rng = rng + 1;
            count = count+u(rng,1);
            if count >= ths
                break;
            end
        end
        return
    end
    %% throw exception if method not known
    ME = MException('selectRange:method', 'No such method : %s', method);
    throw(ME);
end
